﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using Quartz;
using Quartz.Impl;
using System.Reflection;
using Quartz.Impl.Triggers;
using FTchina.Library;
using FTchina.Logic;
using System.Globalization;
using FineUI;
using System.Collections;

public partial class ui_Quartz_Default : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //  Reg("~/quartz/ClassLibrary1.dll", Action.Install);

        if (!IsPostBack)
        {
            InitDrop();
            // BindGrid();
        }
    }

    protected void InitDrop()
    {
        string path = "~/quartz/";
        ddlpath.Label += path;
        ArrayList al = new ArrayList();//排除列表
        al.Add("Quartz.dll".ToUpper());
        al.Add("C5.dll".ToUpper());
        al.Add("Common.Logging.dll".ToUpper());
        al.Add("Topshelf.dll".ToUpper());
        al.Add("Common.Logging.Log4Net.dll".ToUpper());
        al.Add("log4net.dll".ToUpper());
        al.Add("PWMIS.Core.dll".ToUpper());
        al.Add("BaseLibrary.dll".ToUpper());
        

        ddlpath.DataSource = FileHelper.FileInfo2DataTable(path, "*.DLL", al);
        ddlpath.DataTextField = "name";
        ddlpath.DataValueField = "path";
        ddlpath.DataBind();
    }

    #region quartz

    /// <summary>
    /// 操作类型
    /// </summary>
    public enum Action
    {
        /// <summary>
        /// 安装
        /// </summary>
        Install = 1,
        /// <summary>
        /// 启动
        /// </summary>
        Start = 2,
        /// <summary>
        /// 暂停
        /// </summary>
        Pause = 3,
        /// <summary>
        /// 删除
        /// </summary>
        Delete = 4,
        /// <summary>
        /// 恢复
        /// </summary>
        Resume = 5


    }


    /// <summary>
    /// 注册插件状态
    /// </summary>
    /// <param name="path">相对路径</param>
    /// <param name="act">注册行为</param>
    /// <param name="cronExpression">触发器表达式</param>
    /// <param name="cronDescription">触发器描述</param>
    protected void Reg(string path, Action act)
    {
        //path = "~/quartz/ClassLibrary1.dll";
        string FullPath = FileHelper.GetFullPath(path);
        NameValueCollection properties = GetNameValueProperties();//获取配置信息
        ISchedulerFactory factory = new StdSchedulerFactory(properties);//创建工厂
        IScheduler scheduler = factory.GetScheduler();//获取调度实例


        Assembly asm = Assembly.LoadFile(FullPath);//获取反射参数
        Type[] types = asm.GetTypes();

        foreach (Type t in types)
        {
            if (new List<Type>(t.GetInterfaces()).Contains(typeof(IJob)))
            {//只关心实现了Ijob接口的插件


                ///获取描述信息
                object[] r = t.Assembly.GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
                AssemblyDescriptionAttribute descattr = (AssemblyDescriptionAttribute)r[0];

                //创建工作
                IJobDetail job = JobBuilder.Create(t)
                                            .WithIdentity("NA" + t.Name, "GP" + t.Namespace)
                                            .WithDescription(descattr.Description)
                                            .Build();
                scheduler.Start();

                //string cronExpression = "0 0/1 * 1/1 * ? *";//触发器时间
                //string cronDescription = "每分钟执行一次";//触发器描述



                if (act == Action.Install)
                {
                    string cronExpression = txbCronExp.Text.Trim();
                    string cronDescription = TxbCronDesc.Text.Trim();
                    //同名的先删除
                    //scheduler.DeleteJob(job.Key);//删除已有的，会连同trigger一起删除


                    //创建触发器
                    ITrigger trigger = TriggerBuilder.Create()
                                                    .WithIdentity("CT" + t.Name, "TG" + t.Namespace)
                                                    .WithCronSchedule(cronExpression)//触发器表达式
                                                    .WithDescription(cronDescription)//触发器描述
                                                    .Build();
                    scheduler.ScheduleJob(job, trigger);
                    job.GetJobBuilder().StoreDurably(true);//保存

                }

                if (act == Action.Delete)
                {
                    scheduler.DeleteJob(job.Key);//删除已有的，会连同trigger一起删除  

                }

                if (act == Action.Pause)
                {
                    scheduler.PauseJob(job.Key);//暂停job,其实是暂停了Trigger
                }
                if (act == Action.Resume)
                {
                    // scheduler.TriggerJob(job.Key);
                    //scheduler.ResumeJob(job.Key);//恢复job
                    scheduler.ResumeJob(new JobKey("CT" + t.Name, "TG" + t.Namespace));
                }
            }
        }
    }


    /// <summary>
    /// 获取配置
    /// </summary>
    /// <returns></returns>
    private static NameValueCollection GetNameValueProperties()
    {
        NameValueCollection properties = new NameValueCollection();

        properties["quartz.scheduler.instanceName"] = "FTChinaScheduler";
        properties["quartz.scheduler.instanceId"] = "instance_one";
        properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
        properties["quartz.threadPool.threadCount"] = "5";
        properties["quartz.threadPool.threadPriority"] = "Normal";
        properties["quartz.jobStore.misfireThreshold"] = "60000";
        properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
        properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.StdAdoDelegate, Quartz";
        properties["quartz.jobStore.useProperties"] = "false";
        properties["quartz.jobStore.dataSource"] = "default";
        properties["quartz.jobStore.tablePrefix"] = "QRTZ_";
        properties["quartz.jobStore.clustered"] = "true";
        // if running MS SQL Server we need this
        properties["quartz.jobStore.selectWithLockSQL"] = "SELECT * FROM {0}LOCKS UPDLOCK WHERE LOCK_NAME = @lockName";
        properties["quartz.dataSource.default.connectionString"] = @"Server=134.44.36.127;Database=ExtFTchina;User Id=sa;Password=shujuku!!!;";
        properties["quartz.dataSource.default.provider"] = "SqlServer-20";

        //开启远程管理
        properties["quartz.scheduler.exporter.type"] = "Quartz.Simpl.RemotingSchedulerExporter, Quartz";
        properties["quartz.scheduler.exporter.port"] = "5555";
        properties["quartz.scheduler.exporter.bindName"] = "QuartzScheduler";
        properties["quartz.scheduler.exporter.channelType"] = "tcp";


        return properties;
    }
    #endregion


    #region 表格绑定

    //    protected void BindGrid()
    //    {
    //        PWMIS.DataProvider.Data.AdoHelper adohepler = PWMIS.DataProvider.Adapter.MyDB.GetDBHelperByConnectionName("default");
    //        string sql = @"select 
    //                    t.SCHED_NAME,t.JOB_NAME,
    //                    t.JOB_GROUP,t.DESCRIPTION,
    //                    t.JOB_CLASS_NAME,
    //                    t.IS_DURABLE,
    //                    t.IS_NONCONCURRENT,
    //                    t.IS_UPDATE_DATA,
    //                    t.REQUESTS_RECOVERY,
    //                    g.TRIGGER_NAME,
    //                    g.DESCRIPTION as tDESCRIPTION,
    //                    g.TRIGGER_STATE,
    //                    g.PREV_FIRE_TIME,
    //                    g.NEXT_FIRE_TIME,
    //                    p.PATH
    //                    from QRTZ_JOB_DETAILS t,QRTZ_TRIGGERS g ,QRTZ_JobClassName_Path p
    //where t.JOB_NAME=g.JOB_NAME and t.JOB_GROUP=g.JOB_GROUP and t.SCHED_NAME=g.SCHED_NAME and t.JOB_CLASS_NAME=p.JOB_CLASS_NAME
    //order by SCHED_NAME desc";
    //        int Allcount = Convert.ToInt32(adohepler.ExecuteScalar("select Count(*) from QRTZ_JOB_DETAILS").ToString());
    //        Grid1.PageSize = 18;
    //        string singlesql = PWMIS.Common.SQLPage.MakeSQLStringByPage(PWMIS.Common.DBMSType.SqlServer, sql, "", Grid1.PageSize, Grid1.PageIndex + 1, Allcount);
    //        Grid1.RecordCount = Allcount;
    //        Grid1.DataSource = adohepler.ExecuteDataSet(singlesql);
    //        Grid1.DataBind();

    //        // Alert.Show(Allcount.ToString());
    //    }



    //    /// <summary>
    //    /// 分页事件
    //    /// </summary>
    //    /// <param name="sender"></param>
    //    /// <param name="e"></param>
    //    protected void Grid1_PageIndexChange(object sender, FineUI.GridPageEventArgs e)
    //    {

    //        Grid1.PageIndex = e.NewPageIndex;

    //    }
    //    protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
    //    {
    //        string path = Grid1.DataKeys[e.RowIndex][1].ToString();

    //        if (e.CommandName == "Pause")
    //        {
    //            Reg(path, Action.Pause);
    //        }
    //        if (e.CommandName == "Resume")
    //        {
    //            Reg(path, Action.Resume);
    //        }
    //        if (e.CommandName == "Delete")
    //        {
    //            Reg(path, Action.Delete);
    //        }
    //    }
    #endregion


    protected void btnok_Click(object sender, EventArgs e)
    {
        string path = ddlpath.SelectedValue;
        //Alert.Show(path);
        Reg(path, Action.Install);
        AlertLogic.ShowResult(true);
    }
    protected void btnremove_Click(object sender, EventArgs e)
    {
        string path = ddlpath.SelectedValue;
        //Alert.Show(path);
        Reg(path, Action.Delete);
        AlertLogic.ShowResult(true);
    }
    /// <summary>
    /// 数据库里的字符串转化为时间
    /// </summary>
    /// <param name="columnValue"></param>
    /// <returns></returns>
    public DateTime? GetDateTimeFromDbValue(object columnValue)
    {
        if (columnValue != null && columnValue != DBNull.Value)
        {
            var ticks = Convert.ToInt64(columnValue, CultureInfo.CurrentCulture);
            if (ticks > 0)
            {
                return new DateTimeOffset(ticks, TimeSpan.Zero).DateTime.ToLocalTime();
            }
        }
        return null;
    }
}